package com.gitee.huxing.course.conc.conc03.collection;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description:
 * @ProjectName: JavaCourse
 * @Package: com.gitee.huxing.course.conc.conc03.collection
 * @ClassName: ConcurrentHashMapDemo
 * @Author: huxingmale
 * @DateTime: 2021-08-25 20:55
 */
public class ConcurrentHashMapDemo {

    public static void main(String[] args) {
            demo1();
    }

    public static void demo1(){
        final Map<String, AtomicInteger> count = new ConcurrentHashMap<>();
        final CountDownLatch endLatch = new CountDownLatch(2);
        Runnable task = () -> {
            AtomicInteger oldValue;
            for (int i = 0; i < 5; i++) {
                oldValue = count.get("a");
                if (null == oldValue){
                    AtomicInteger zeroValue = new AtomicInteger(0);
                    oldValue = count.putIfAbsent("a", zeroValue);
                    if (null == oldValue){
                        oldValue = zeroValue;
                    }
                }
                oldValue.getAndIncrement();
            }
            endLatch.countDown();
        };
        new Thread(task).start();
        new Thread(task).start();
        try {
            endLatch.await();
            System.out.println(count);
        } catch (Exception ex){
            ex.printStackTrace();
        }
    }
}
